package com.yachang.qym.usbhost.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.github.nkzawa.emitter.Emitter;
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;
import com.google.gson.JsonObject;
import com.snappydb.DB;
import com.snappydb.SnappydbException;
import com.yachang.qym.usbhost.R;
import com.yachang.qym.usbhost.UsbApplication;
import com.yachang.qym.usbhost.adapter.FireCompanyAdapter;
import com.yachang.qym.usbhost.adapter.UserAdapter;
import com.yachang.qym.usbhost.model.FireCompanyModel;
import com.yachang.qym.usbhost.model.MessageModel;
import com.yachang.qym.usbhost.model.OutPoliceModel;
import com.yachang.qym.usbhost.model.UserModel;
import com.yachang.qym.usbhost.utils.API;
import com.yachang.qym.usbhost.utils.AllData;
import com.yachang.qym.usbhost.utils.MessageCache;
import com.yachang.qym.usbhost.utils.ToastUtil;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.yachang.qym.usbhost.utils.API.mSocket;
import static com.yachang.qym.usbhost.utils.API.serverUrl;

public class LoginActivity extends AppCompatActivity {
    private GridView mGvUser;
    private TextView mTvFireCompany;
    private RelativeLayout mLayoutMore;
    private Button mBtnLogin;
    private PopupWindow popupWindow;
    private Toolbar mToolbar;
    private View mViewDiv;
    private UserAdapter mUserAdapter;
    private List<FireCompanyModel> fireCompanyModels = new ArrayList<>();
    private List<UserModel> userModels = new ArrayList<>();
    private UserModel mUserModel = null;
    private boolean isNetRunning = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(AllData.isLogin){
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            LoginActivity.this.finish();
        }else {
            setContentView(R.layout.activity_login);
            getFireCompanyData();
            initView();
        }
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    private void initView(){
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setTitle("登录");
        mViewDiv = findViewById(R.id.view_div);
        mGvUser = (GridView) findViewById(R.id.gv_user_list);
        mTvFireCompany = (TextView) findViewById(R.id.tv_fire_company);
        mLayoutMore = (RelativeLayout) findViewById(R.id.layout_company_more);
        mBtnLogin = (Button) findViewById(R.id.btn_login);
        mLayoutMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopup();
            }
        });

        mGvUser.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mUserAdapter.choosePosition = position;
                mUserAdapter.notifyDataSetChanged();
                mUserModel = userModels.get(position);
            }
        });
        mBtnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mUserModel == null){
                    ToastUtil.showToast("请选择需登录的用户！");
                }else {
                    try {
                        mSocket = IO.socket(serverUrl);
                    } catch (URISyntaxException e) {
                        Log.e("SocketConnectError", e.getMessage());
                    }
                    mSocket.connect();
                    for(UserModel model: userModels){

                        MessageCache.msg.put(model.get_id(), new ArrayList<MessageModel>());

                    }
                    AllData.userModel = mUserModel;
                    AllData.isLogin = true;
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    intent.putExtra("isNetRunning", isNetRunning);
                    startActivity(intent);
                    LoginActivity.this.finish();
                }
            }
        });
    }

    public void showPopup() {
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.popup_parent, null);
        ListView listView = (ListView) contentView.findViewById(R.id.lv_fire_company_list);
        FireCompanyAdapter adapter = new FireCompanyAdapter(this, fireCompanyModels);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mViewDiv.setVisibility(View.VISIBLE);
                mTvFireCompany.setText(fireCompanyModels.get(position).getName());
                popupWindow.dismiss();
                getUsersData(fireCompanyModels.get(position).get_id());
            }
        });

        popupWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setTouchable(true);

        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        popupWindow.setAnimationStyle(R.style.PopupAnimation);
        popupWindow.showAsDropDown(mLayoutMore);

        popupWindow.update();
    }

    public void getFireCompanyData() {
        JsonObjectRequest ja = new JsonObjectRequest(Request.Method.GET, API.getFireCompanyUrl(), null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONArray array = response.getJSONArray("result");
                    for (int i = 0; i < array.length(); i++) {
                        FireCompanyModel data = new FireCompanyModel();
                        JSONObject object = array.getJSONObject(i);
                        Gson gson = new Gson();
                        data = gson.fromJson(String.valueOf(object), FireCompanyModel.class);
                        fireCompanyModels.add(data);
                    }
                    DB db = UsbApplication.getDB();
                    Object[] fireCompany = fireCompanyModels.toArray();
                    db.put("firecompany", fireCompany);
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (SnappydbException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                ToastUtil.showToast("网络连接异常，进入无网络模式！");
                DB db = UsbApplication.getDB();
                try {
                    FireCompanyModel[] fireCompanyModels1;
                    fireCompanyModels1 = db.getObjectArray("firecompany", FireCompanyModel.class);
                    fireCompanyModels = Arrays.asList(fireCompanyModels1);
                } catch (SnappydbException e) {
                    e.printStackTrace();
                }
            }
        });
        RequestQueue queue = UsbApplication.getQueue();
        queue.add(ja);
    }

    public void getUsersData(final String fid){
        Map<String, Object> map = new HashMap<>();
        map.put("fid" ,fid);
        map.put("state" ,true);
        JSONObject jsonObject = new JSONObject(map);
        JsonObjectRequest ja = new JsonObjectRequest(Request.Method.POST, API.getFireCompanyUserUrl(), jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONArray array = response.getJSONArray("result");
                    userModels = new ArrayList<>();
                    for (int i = 0; i < array.length(); i++) {
                        UserModel userModel = new UserModel();
                        JSONObject object = array.getJSONObject(i);
                        Gson gson = new Gson();
                        userModel = gson.fromJson(String.valueOf(object), UserModel.class);


                           if(userModel.isLogin()){
                               userModel.setImageUrl("http://www.cdyachang.com:8080/image/e9450d20-a28b-11e7-a17d-a315fa85a39cbase64.png");
                           }
                        userModels.add(userModel);
                    }
                    mGvUser.setVisibility(View.VISIBLE);
                    mUserAdapter = new UserAdapter(LoginActivity.this, userModels);

                    mGvUser.setAdapter(mUserAdapter);
                    DB db = UsbApplication.getDB();
                    Object[] users = userModels.toArray();

                    db.put(fid, users);
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (SnappydbException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                ToastUtil.showToast("网络连接异常，进入无网络模式！");
                DB db = UsbApplication.getDB();
                try {
                    UserModel[] userModels1;
                    userModels1 = db.getObjectArray(fid, UserModel.class);
                    userModels = Arrays.asList(userModels1);

                    mGvUser.setVisibility(View.VISIBLE);
                    mUserAdapter = new UserAdapter(LoginActivity.this, userModels);
                    mGvUser.setAdapter(mUserAdapter);
                    isNetRunning = false;
                } catch (SnappydbException e) {
                    e.printStackTrace();
                }
            }
        });
        RequestQueue queue = UsbApplication.getQueue();
        queue.add(ja);
    }


 public  void changeIsLogin(final String fid){

     Map<String, Object> map = new HashMap<>();
     map.put("fid" ,fid);
     map.put("state" ,true);
     JSONObject jsonObject = new JSONObject(map);
     JsonObjectRequest ja = new JsonObjectRequest(Request.Method.POST, API.getFireCompanyUserUrl(), jsonObject, new Response.Listener<JSONObject>() {
         @Override
         public void onResponse(JSONObject response) {
             try {
                 JSONArray array = response.getJSONArray("result");
                 userModels = new ArrayList<>();
                 for (int i = 0; i < array.length(); i++) {
                     UserModel userModel = new UserModel();
                     JSONObject object = array.getJSONObject(i);
                     Gson gson = new Gson();
                     userModel = gson.fromJson(String.valueOf(object), UserModel.class);
                     userModel.setLogin(true);
                     userModels.add(userModel);
                 }

             } catch (JSONException e) {
                 e.printStackTrace();
             }
         }
     }, new Response.ErrorListener() {
         @Override
         public void onErrorResponse(VolleyError error) {

         }
     });
     RequestQueue queue = UsbApplication.getQueue();
     queue.add(ja);
 }



}
